<?php
namespace app\api\controller;

use app\api\model\Notification as NotificationModel;
use app\api\model\MemberNotification;
use think\Request;

/**
 * 通知API控制器
 * Class Notification
 * @package app\api\controller
 */
class Notification extends BaseController
{
    /**
     * 获取通知列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getList(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }
        
        // 获取请求参数
        $page = $request->param('page', 1);
        $limit = $request->param('limit', 10);
        $type = $request->param('type', ''); // 通知类型
        
        // 查询条件
        $where = [
            'status' => 1, // 只获取已发布的通知
        ];
        
        // 如果指定了通知类型，则按类型筛选
        if (!empty($type)) {
            $where['type'] = $type;
        }
        
        // 查询通知列表
        $list = NotificationModel::alias('n')
            ->leftJoin('park_member_notification mn', "mn.notification_id = n.id AND mn.member_id = {$this->userId}")
            ->where($where)
            ->field('n.id, n.title, n.content, n.type, n.create_time, IFNULL(mn.is_read, 0) as is_read')
            ->order(['n.id' => 'desc'])
            ->page($page, $limit)
            ->select();
            
        // 处理数据
        foreach ($list as &$item) {
            $item['create_time_text'] = date('Y-m-d H:i', $item['create_time']);
            $item['is_read'] = (int)$item['is_read'];
        }
        
        // 获取总记录数
        $total = NotificationModel::where($where)->count();
        
        // 获取未读通知数量
        $unreadCount = NotificationModel::alias('n')
            ->leftJoin('park_member_notification mn', "mn.notification_id = n.id AND mn.member_id = {$this->userId}")
            ->where($where)
            ->where('IFNULL(mn.is_read, 0) = 0')
            ->count();
        
        return $this->renderSuccess('获取成功', [
            'list' => $list,
            'total' => $total,
            'unread_count' => $unreadCount,
            'page' => $page,
            'limit' => $limit,
            'page_count' => ceil($total / $limit)
        ]);
    }
    
    /**
     * 获取通知详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function detail(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }
        
        // 获取请求参数
        $id = $request->param('id');
        
        if (empty($id)) {
            return $this->renderError('参数错误：缺少通知ID');
        }
        
        // 查询通知详情
        $detail = NotificationModel::where([
            'id' => $id,
            'status' => 1
        ])->find();
        
        if (!$detail) {
            return $this->renderError('通知不存在或已下线');
        }
        
        // 处理数据
        $detail['create_time_text'] = date('Y-m-d H:i', $detail['create_time']);
        
        // 标记为已读
        $memberNotification = MemberNotification::where([
            'member_id' => $this->userId,
            'notification_id' => $id
        ])->find();
        
        if (!$memberNotification) {
            // 创建已读记录
            $memberNotification = new MemberNotification;
            $memberNotification->member_id = $this->userId;
            $memberNotification->notification_id = $id;
            $memberNotification->is_read = 1;
            $memberNotification->read_time = time();
            $memberNotification->save();
        } else if ($memberNotification['is_read'] == 0) {
            // 更新为已读
            $memberNotification->is_read = 1;
            $memberNotification->read_time = time();
            $memberNotification->save();
        }
        
        return $this->renderSuccess('获取成功', $detail);
    }
    
    /**
     * 标记通知为已读
     * @param Request $request
     * @return \think\response\Json
     */
    public function read(Request $request)
    {
        if (!$this->checkToken()) {
            return false;
        }
        
        // 获取请求参数
        $id = $request->param('id');
        $readAll = $request->param('read_all', 0);
        
        if (empty($id) && $readAll != 1) {
            return $this->renderError('参数错误：缺少通知ID');
        }
        
        if ($readAll == 1) {
            // 标记所有通知为已读
            $notificationIds = NotificationModel::where('status', 1)->column('id');
            
            foreach ($notificationIds as $notificationId) {
                $memberNotification = MemberNotification::where([
                    'member_id' => $this->userId,
                    'notification_id' => $notificationId
                ])->find();
                
                if (!$memberNotification) {
                    // 创建已读记录
                    $memberNotification = new MemberNotification;
                    $memberNotification->member_id = $this->userId;
                    $memberNotification->notification_id = $notificationId;
                    $memberNotification->is_read = 1;
                    $memberNotification->read_time = time();
                    $memberNotification->save();
                } else if ($memberNotification['is_read'] == 0) {
                    // 更新为已读
                    $memberNotification->is_read = 1;
                    $memberNotification->read_time = time();
                    $memberNotification->save();
                }
            }
            
            return $this->renderSuccess('已全部标记为已读');
        } else {
            // 标记单条通知为已读
            $memberNotification = MemberNotification::where([
                'member_id' => $this->userId,
                'notification_id' => $id
            ])->find();
            
            if (!$memberNotification) {
                // 创建已读记录
                $memberNotification = new MemberNotification;
                $memberNotification->member_id = $this->userId;
                $memberNotification->notification_id = $id;
                $memberNotification->is_read = 1;
                $memberNotification->read_time = time();
                $memberNotification->save();
            } else if ($memberNotification['is_read'] == 0) {
                // 更新为已读
                $memberNotification->is_read = 1;
                $memberNotification->read_time = time();
                $memberNotification->save();
            }
            
            return $this->renderSuccess('已标记为已读');
        }
    }
} 